package com.turing.usdtpay.mvp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.turing.usdtpay.R;
import com.turing.usdtpay.base.BaseActivity;
import com.turing.usdtpay.entity.PayData;
import com.turing.usdtpay.entity.SettingData;
import com.turing.usdtpay.http.ApiUrl;
import com.turing.usdtpay.mvp.contract.PaySettingContract;
import com.turing.usdtpay.mvp.dialog.QRDialog;
import com.turing.usdtpay.mvp.presenter.PaySettingPresenter;
import com.turing.usdtpay.mvp.view.BaseTitleView;
import com.turing.usdtpay.mvp.view.CircularProgressView;
import com.turing.usdtpay.mvp.view.popwindow.CommonPopupWindow;
import com.turing.usdtpay.mvp.view.popwindow.PayTypePopWindow;
import com.turing.usdtpay.utils.DipPxUtils;
import com.turing.usdtpay.utils.LogUtils;
import com.turing.usdtpay.utils.PhotoUtils;
import com.turing.usdtpay.utils.QRCodeUtil;
import com.turing.usdtpay.utils.ToastUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @作者：JAY
 * @创建时间：2019/10/16 17:52
 * @描述：
 **/
public class PayActivity extends Activity implements View.OnClickListener, PaySettingContract.View, PayTypePopWindow.OnClickListener {
    private String TAG = "AccountFragment";
    private BaseTitleView mTitle;
    private Button mCommit, mTest;
    private EditText mName, mAccountEt;
    private TextView mType, mAccountTv;
    private ImageView mQRCode;
    private int mPayType = 3; //默认支付渠道是支付宝 1.银行卡 2.微信 3.支付宝
    private String mQRCodeText = "";
    private PaySettingContract.Present mPresent;
    private CircularProgressView mCircularProgress;
    private boolean mAlipayUpload, mWechatUpload;
    private ProgressBar mProgress;
    private List<SettingData> mChannelData = null;
    private PayTypePopWindow mPopWindow;
    private Bitmap mBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        initView();
        initTitle();
        setPresenter(new PaySettingPresenter(this));
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        PayData data = (PayData) intent.getSerializableExtra("data");
        if (data != null){
            List<SettingData> set_info = data.getSet_info();
            if (set_info == null || set_info.size() < 1) {
                return;
            }
            mChannelData = set_info;
            SettingData settingData = set_info.get(0);
            int channel = settingData.getChannel();
            String code_url = settingData.getCode_url();
            String name = settingData.getName();
            String account = settingData.getBank_id();
            mName.setText(name);
            mAccountEt.setText(account);
            LogUtils.d(TAG,"加载 url -->"+code_url);
            if (channel == 3) {
                updateInfo(3, "支付宝", "支付宝账号", R.drawable.btn_blue_bg, code_url);
            } else {
                updateInfo(2, "微信", "微信账号", R.drawable.btn_green_bg, code_url);
            }
        }

    }

    private void initTitle() {
        mTitle.setLeftShow(true);
        mTitle.setLeftButtonListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(2,intent);
                finish();
            }
        });
        mTitle.setTitle("支付设置");
    }

    private void initView() {
        mTitle = (BaseTitleView) findViewById(R.id.title);
        mCommit = (Button) findViewById(R.id.btn_commit);
        mTest = (Button) findViewById(R.id.btn_test);
        mName = (EditText) findViewById(R.id.et_name);
        mAccountEt = (EditText) findViewById(R.id.et_account);
        mAccountTv = (TextView) findViewById(R.id.tv_account);
        mType = (TextView) findViewById(R.id.tv_type);
        mQRCode = (ImageView) findViewById(R.id.iv_qr_code);
        mCircularProgress = (CircularProgressView) findViewById(R.id.circular_progress);
        mProgress = (ProgressBar) findViewById(R.id.progress);
        mType.setOnClickListener(this);
        mQRCode.setOnClickListener(this);
        mTest.setOnClickListener(this);
        mCommit.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == mType.getId()) {
            mPopWindow = new PayTypePopWindow(this, R.layout.popwindow_pay_type, mType.getWidth(), 200);
            mPopWindow.setListener(this);
            mPopWindow.showAsDropDown(mType);
        } else if (v.getId() == mCommit.getId()) {
            if (!TextUtils.isEmpty(mName.getText().toString()) && !TextUtils.isEmpty(mAccountEt.getText().toString())) {
                if (mPayType == 2) {
                    if (mWechatUpload) {
                        mProgress.setVisibility(View.VISIBLE);
                        mPresent.saveSetting(this, mPayType, mName.getText().toString(), "微信", mAccountEt.getText().toString());
                    } else {
                        ToastUtils.showNormolToast(this, "请上传微信二维码");
                    }
                } else {
                    if (mAlipayUpload) {
                        mProgress.setVisibility(View.VISIBLE);
                        mPresent.saveSetting(this, mPayType, mName.getText().toString(), "支付宝", mAccountEt.getText().toString());
                    } else {
                        ToastUtils.showNormolToast(this, "请上传支付宝二维码");
                    }
                }
            } else {
                ToastUtils.showNormolToast(this, "姓名和账号不能为空");
            }
        } else if (v.getId() == mTest.getId()) {
            if (mBitmap != null) {
                QRDialog dialog = new QRDialog(this);
                dialog.show();
                dialog.showQRCodeByBitmap(mBitmap);
            } else {
                ToastUtils.showNormolToast(PayActivity.this, "请上传二维码");
            }
        } else if (v.getId() == mQRCode.getId()) {
            PhotoUtils.selectPic(this, 1);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1001:
                    PhotoUtils.cropPhoto(this, PhotoUtils.uriImage, true);
                    break;
                case 1002:
                    if (data != null) {
                        Uri uri = data.getData();
                        PhotoUtils.cropPhoto(this, uri, false);
                    }
                    break;
                case 1003:
                    try {
                        mBitmap = getBitmapFormUri(this, PhotoUtils.CutUri);
                        mQRCodeText = QRCodeUtil.getCodeText(mBitmap);
                        LogUtils.d("二维码 --》" + mQRCodeText);
                        boolean b = QRCodeUtil.isQRCode(mBitmap);
                        if (b) {
                            String path = PhotoUtils.getRealPathFromUri(this, PhotoUtils.CutUri);
                            mQRCode.setPadding(20, 20, 20, 20);
                            mQRCode.setImageURI(PhotoUtils.CutUri);
                            int type = 0;
                            if (mPayType == 3) {
                                type = 2;   //支付宝
                            } else {
                                type = 1;   //微信
                            }
                            mCircularProgress.setVisibility(View.VISIBLE);
                            mCircularProgress.setProgress(0);
                            mPresent.uploadImage(PayActivity.this, "", type, new File(path));
                        } else {
                            ToastUtils.showNormolToast(PayActivity.this, "请裁剪有效二维码");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    }

    /**
     * 通过uri获取图片并进行压缩
     *
     * @param uri
     */
    public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
        InputStream input = ac.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
        //图片分辨率以480x800为标准
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = ac.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    @Override
    public void saveSuccess() {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this, "保存成功");
        Intent intent = new Intent();
        setResult(2,intent);
        finish();
    }

    @Override
    public void getSuccess(PayData data) {

    }

    private void updateInfo(int pay_type, String type, String acc, int res_bg, final String url) {
        mPayType = pay_type;
        mType.setText(type);
        mAccountTv.setText(acc);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mQRCode.setBackground(getResources().getDrawable(res_bg));
        }
        if (TextUtils.isEmpty(url)) {
            if (pay_type == 3) {
                mQRCode.setPadding(DipPxUtils.dip2px(PayActivity.this, 30)
                        , DipPxUtils.dip2px(PayActivity.this, 30)
                        , DipPxUtils.dip2px(PayActivity.this, 30)
                        , DipPxUtils.dip2px(PayActivity.this, 30));
                mQRCode.setImageResource(R.mipmap.btn_add_white);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mQRCode.setBackground(getResources().getDrawable(R.drawable.btn_blue_bg));
                }
            } else {
                mQRCode.setPadding(DipPxUtils.dip2px(PayActivity.this, 30)
                        , DipPxUtils.dip2px(PayActivity.this, 30)
                        , DipPxUtils.dip2px(PayActivity.this, 30)
                        , DipPxUtils.dip2px(PayActivity.this, 30));
                mQRCode.setImageResource(R.mipmap.btn_add_white);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mQRCode.setBackground(getResources().getDrawable(R.drawable.btn_green_bg));
                }
            }

        } else {
            if (pay_type == 2) {
                mWechatUpload = true;
            } else if (pay_type == 3) {
                mAlipayUpload = true;
            }
            Picasso.get().load(ApiUrl.API_BASE_URL + url).into(mQRCode);
            mQRCode.setPadding(20, 20, 20, 20);
            Picasso.get().load(ApiUrl.API_BASE_URL + url).memoryPolicy(MemoryPolicy.NO_CACHE).into(mQRCode);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mBitmap = Picasso.get().load(ApiUrl.API_BASE_URL + url).get();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            if (pay_type == 3) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mQRCode.setBackground(getResources().getDrawable(R.drawable.btn_blue_bg));
                }
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mQRCode.setBackground(getResources().getDrawable(R.drawable.btn_green_bg));
                }
            }
        }
    }

    @Override
    public void uploadSuccess(int type) {
        if (type == 1) {     //微信
            mWechatUpload = true;
            mAlipayUpload = false;
        } else {     //支付宝
            mAlipayUpload = true;
            mWechatUpload = false;
        }
        mCircularProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this, "上传成功");
    }

    @Override
    public void onFail(String msg) {
        mProgress.setVisibility(View.GONE);
        mCircularProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this, msg);
    }

    @Override
    public void onProgress(int progress) {
        mCircularProgress.setProgress(progress);
    }

    @Override
    public void setPresenter(PaySettingContract.Present presenter) {
        mPresent = presenter;
    }

    //选择弹出的点击事件
    @Override
    public void onClick(int type) {
        if (type == 1) {
            if (mChannelData == null) {
                mAlipayUpload = false;
                updateInfo(3, "支付宝", "支付宝账号", R.drawable.btn_blue_bg, "");
                return;
            }
            for (SettingData data : mChannelData) {
                if (data.getChannel() == 3) {
                    String name = data.getName();
                    String account = data.getBank_id();
                    mName.setText(name);
                    mAccountEt.setText(account);
                    LogUtils.d(TAG,"点击 url -->"+data.getCode_url());
                    updateInfo(3, "支付宝", "支付宝账号", R.drawable.btn_blue_bg, data.getCode_url());
                    return;
                }
            }
            mAlipayUpload = false;
            updateInfo(3, "支付宝", "支付宝账号", R.drawable.btn_blue_bg, "");
            mPopWindow.dismiss();
        } else {
            if (mChannelData == null) {
                mWechatUpload = false;
                updateInfo(2, "微信", "微信账号", R.drawable.btn_green_bg, "");
                return;
            }
            for (SettingData data : mChannelData) {
                if (data.getChannel() == 2) {
                    String name = data.getName();
                    String account = data.getBank_id();
                    mName.setText(name);
                    mAccountEt.setText(account);
                    LogUtils.d(TAG,"点击 url -->"+data.getCode_url());
                    updateInfo(2, "微信", "微信账号", R.drawable.btn_blue_bg, data.getCode_url());
                    return;
                }
            }
            mWechatUpload = false;
            updateInfo(2, "微信", "微信账号", R.drawable.btn_green_bg, "");
        }

    }
}
